package com.demo.springboothexadecimalconversion.hextobyte;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author Hanson
 * @date 2022/12/14 22:44
 */
@Slf4j
public class IsEffectiveDate {

    @Test
    public void test() {
        Long timeStamp = System.currentTimeMillis();  //获取当前时间戳
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String sd = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp))));

        Boolean runFlag = null;
        Date nowTime;
        try {
            nowTime = sdf.parse(sd);
            Date startTime = sdf.parse("07:00:00");
            Date endTime = sdf.parse("23:00:00");
            if (isEffectiveDate(nowTime, startTime, endTime)) {
                runFlag = true;
                log.info("当前时间在晚上23点到早上7点之间.");
            } else {
                runFlag = false;
                log.info("当前时间不在晚上23点到早上7点之间.");
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        System.out.println(runFlag);
    }

    /**
     * 判断当前时间是否在[endTime,startTime]区间，注意时间格式要一致
     *
     * @param nowTime   当前时间
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     * @author jqlin
     */
    public boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        return !(date.after(begin) && date.before(end));
    }
}
